<?php

/**
 * 夏日葵电商系统
 * http://www.xiarikui.com
 */

namespace Xcx\Model;

use Think\Model\RelationModel;
use Xcx\Model\AnswerModel;
use Xcx\Model\UsersModel;
use Xcx\Model\AccountantModel;

/**
 * Class QuestionModel
 * @package Home\Model
 */
class QuestionModel extends RelationModel {


    public function __construct() {
        parent::__construct();
        $this->answerModel = new AnswerModel();
        $this->user_id = session('user_id');
    }

    public function getInfoById($id) {
        $id = $id ? $id : 0;
        $find = M('question')->alias('q')->join('left join __USERS__ as u on q.user_id = u.user_id and u.is_lock = 0')
            ->field('q.*,u.username,u.mobile,u.sex,u.head_pic')
            ->where('q.id = '.$id)->find();
        if($find){
            $find['head_pic'] = (strpos($find['head_pic'],'http') === false && $find['head_pic']) ? SITE_URL.$find['head_pic'] : $find['head_pic'];
            $find['cats_name'] = getCatName($find['cat_ids']);
            $find['response_sec_desc'] = cacTime($find['response_sec']);
            $find['question_status_desc'] = getQuestionStatus($find['question_status']);
            $find['answer_status_desc'] = getAnswerStatus($find['answer_status']);
            $find['stop_time'] = date('Y-m-d H:i:s',$find['stop_time']);
            $find['add_time'] = date('Y-m-d H:i:s',$find['add_time']);
        }else{
            return false;
        }
        return $find;
    }

    public function getList($where = '',$page = 1,$limit = 6,$cac_count = false,$orderby = '',$is_home = false) {
        if($is_home) {
            $where = $where ? $where . ' and q.answer_status = 2 ' : ' q.answer_status = 2 ';
        }
        $select = M('question')->alias('q')
            ->join('left join __ANSWER__ as a on a.question_id = q.id')
            ->join('left join __ACCOUNTANT_USERS__ as au on a.accountant_id = au.au_id and au.status = 1')
            ->join('left join __USERS__ as u on q.user_id = u.user_id and u.is_lock = 0')

            ->field('q.id,q.title,q.has_read,q.answer_status,q.question_status,q.add_time as q_time,a.charge_view,a.charge_money,a.id as a_id,au.username as answer_name,au.head_pic as answer_pic,u.username as nickname')
            ->where($where);
        if($cac_count){
            return $select->count();
        }
        $select = $select->where($where)->page($page,$limit)->order($orderby)->select();
        if($select){
            $arr = array();
            foreach ($select as $find) {
                $temp['id'] = $find['id'];
                $temp['problem'] = $find['title'];
                $temp['nickname'] = $find['nickname'];
                $temp['has_response'] = $find['a_id'] > 0 ? ($find['has_read'] ? false : true) : false;
                $temp['accountant_head'] = (strpos($find['answer_pic'],'http') === false && $find['answer_pic']) ? SITE_URL.$find['answer_pic'] : $find['answer_pic'];
                $temp['accountant_name'] = $find['answer_name'];
                $temp['price'] = $find['charge_view'] ? $find['charge_money'] : 0;
                //$temp['state'] = $find['answer_status'] == 2 ? 1 : 0;
                $temp['answer_state'] = $find['answer_status'];
                $temp['question_state'] = $find['question_status'];
                $temp['state_desc'] = $find['answer_status'] == 2 ? getAnswerStatus($find['answer_status']) : getQuestionStatus($find['question_status']);
                $temp['date_time'] = date('Y-m-d H:i', $find['q_time']);

                $arr[] = $temp;
            }
        }else{
            return false;
        }
        return $arr;
    }



    public function getQuestionByIdWithAnswer($id) {
        $id = $id ? $id : 0;
        $find = $this->getInfoById($id);
        if($find) {
            if($find['user_id'] != $this->user_id) {
                M('question')->where('id = ' . $id)->setInc('read_num', 1); //+1
            }
            //是否已经支付悬赏
            if ($find['question_status'] == 1){
                if($find['user_id'] == $this->user_id){
                    $find['global_status'] = 1;
                }else{
                    $find['global_status'] = 3;
                }

            }elseif ($find['open_reward'] == 1){
                $userModel = new UsersModel();
                $type = $find['question_status'] == 3 ? 1 : 0;
                $hasPay = $userModel->isPayByQuestionId($id, $find['user_id'], $type);
                if($hasPay){
                    $find['answer_arr'] = $this->answerModel->getInfoByQuestionId($find['id']);
                    $find['global_status'] = $find['answer_arr']['global_status'];
                }elseif($find['user_id'] == $this->user_id){
                    $find['global_status'] = 1;
                }else{
                    $find['global_status'] = 3;
                }
            }else{
                $find['answer_arr'] = $this->answerModel->getInfoByQuestionId($find['id']);
                $find['global_status'] = $find['answer_arr']['global_status'];
            }

            //用户是否已读
            if(!$find['has_read'] && $find['user_id'] == $this->user_id && $find['answer_arr']) {
                M('question')->where('id = ' . $id)->setField('has_read', 1);
            }

            return $find;
        }
        return false;
    }

    public function getCollectByUser($user_id = 0,$page = 1,$limit = 6,$cac_count = false) {
        $where = ' 1=1 ';
        if($user_id){
            $where.= ' and c.user_id = '.$user_id;
        }else{
            $where.= ' and c.user_id = 0';
        }
        $select = M('collect')->alias('c')
            ->join('left join __QUESTION__ as q on c.question_id = q.id')
            ->join('left join __USERS__ as u on q.user_id = u.user_id and u.is_lock = 0')
            ->field('q.id,q.title,q.desc,q.add_time,q.question_status,q.answer_status,u.username')
            ->where($where);
        if($cac_count){
            return $select->count();
        }
        $select = $select->page($page,$limit)->order('c.add_time desc')->select();
        if($select){
            foreach ($select as &$find) {
                $find['problem'] = $find['title'] ;
                $find['nickname'] = $find['username'] ;
                $find['accountant_name'] = '';
                $find['question_state'] = $find['question_status'];
                if($find['question_status'] == 3){
                    $answer = $this->answerModel->getUserByQuestionId($find['id']);
                    $find['accountant_name'] = $answer['username'];
                    $find['state_desc'] = getAnswerStatus($find['answer_status']);
                }else{
                    $find['state_desc'] = getQuestionStatus($find['question_status']);
                }

                //$find['answer_status_desc'] = getAnswerStatus($find['answer_status']);
                $find['date_time'] = date('Y-m-d H:i:s', $find['add_time']);
                unset($find['question_status']);
            }
        }else{
            return false;
        }
        return $select;
    }

    public function push($post = array()){
        $res = array('status' => 0 , 'msg' => '' , 'result' => '');
        $title_len = mb_strlen($post['problem'],'utf-8');
        $desc_len = mb_strlen($post['additional'],'utf-8');
        if($title_len < 6 || $title_len > 30){
            $res['msg'] = '问题标题须在6-30个字符内';
            return $res;
        }
        if($desc_len > 300){
            $res['msg'] = '问题描述须在300个字符内';
            return $res;
        }
        if(!$post['class_list']){
            $res['msg'] = '请选择专业类型';
            return $res;
        }
        if(!$post['end_date_time']){
            $res['msg'] = '请填写截止时间';
            return $res;
        }
        if((float)$post['price'] > 0){
            $price = (float)$post['price'];
            $open_reward = 1;
            $question_status = 1;
            //$stop_time = 0;
        }else{
            $price = 0;
            $open_reward = 0;
            $question_status = 2;
            //$stop_time = time() + (getNormalHour() * 60 * 60);
        }

        if(is_array($post['class_list'])){
            $post['class_list'] = implode(',',$post['class_list']);
        }
        $Question = M('question');
        $Question->startTrans();
        $q_id = $Question->data(array(
            'title' => htmlspecialchars($post['problem']),
            'desc' => htmlspecialchars($post['additional']),
            'user_id' => $this->user_id,
            'cat_ids' => $post['class_list'],
            'stop_time' => strtotime($post['end_date_time']),
            'read_num' => 0,
            'response_sec' => 0,
            'open_reward' => $open_reward,
            'reward_money' => $price,
            'question_status' => $question_status,
            'answer_status' => 1,
            'add_time' => time(),
        ))->add();
        if(!$q_id){
            $Question->rollback();
            $res['msg'] = '数据保存失败';
            return $res;
        }

        if ($post['assign_id'] > 0) {
            $accModel = new AccountantModel();
            $acinfo = $accModel->getInfoById($post['assign_id']);
            if(!$acinfo){
                $Question->rollback();
                $res['msg'] = '查找不到指定会计师信息';
                return $res;
            }
            $time = getPromptDay() * 86400;
            if($acinfo['expired_time'] + $time < time()){
                $Question->rollback();
                $res['msg'] = '该会计师已欠费，无法对其提问';
                return $res;
            }
            $bool = M('question_answer')->data(array(
                'question_id' => $q_id,
                'answer_id' => $post['assign_id'],
                'update_time' => time(),
                'add_time' => time(),
            ))->add();
        } else {
            $bool = $this->randomQuestionToAnswer($q_id);
        }

        if($bool){
            if($question_status != 1 ) {//待支付的暂时不推送
                jpush($q_id);
            }
            $res['result'] = array('problem_id' => $q_id);

            $Question->commit();
        }else{
            $Question->rollback();
        }

        $res['status'] = $bool ? true : false;
        $res['msg'] = $bool ? 'success' : 'fail';
        return $res;
    }

    public function randomQuestionToAnswer($q_id){
        $city = M('users')->where('user_id = '.$this->user_id)->getField('city');
        $cat_ids = M('question')->where('id = '.$q_id)->getField('cat_ids');
        $cat_name = getCatName($cat_ids);
        $time = getPromptDay() * 86400;
        $select = M('accountant_users')->alias('au')
            ->join('left join __QUESTION_ANSWER__ as qa on au.au_id = qa.answer_id')
            ->where('au.city = '.$city.' and status = 1 and (au.expired_time + '.$time.' > '.time().') ')
            ->field('au.au_id,au.cat_ids,count(qa.answer_id) as count')
            ->group('au.au_id')
            ->select();
        $has_type = array(); //同地区有相同专业的
        $no_type = array(); //同地区无相同专业的

        foreach($select as $item){
            $ex = explode(',',$item['cat_ids']);
            $bool = true;
            foreach($cat_name as $id=>$val){
                if(in_array($id,$ex)){
                    $has_type[$item['count']][] = $item['au_id'];
                    $bool = false;
                }
            }
            if($bool){
                $no_type[$item['count']][] = $item['au_id'];
            }
        }

        $temp = $has_type ? $has_type : $no_type;
        if(empty($temp)){
           $other = M('accountant_users')->where('status = 1 and ( expired_time + '.$time.' > '.time().' ) ')->order('rand()')->field('au_id')->find();
            $arr = array($other['au_id']);
        }else{
            ksort($temp);
            $arr = current($temp);
        }

        $random = rand(0,count($arr) - 1);
        if(!$arr[$random]){
            return false;
        }
        return M('question_answer')->data(array(
            'question_id' => $q_id,
            'answer_id' => $arr[$random],
            'update_time' => time(),
            'add_time' => time(),
        ))->add();
    }

    public function delQuestion($q_id){
        $q_id = $q_id ? $q_id : 0;
        return M('question')->where('id = '.$q_id)->delete();
    }

    public function adoption($post = array()){
        $res = array('status' => 0 , 'msg' => '');

        $accModel = new AccountantModel();
        $id = $accModel->hasAdoption($post['question_id'],$post['accounting_id']);

        if($id){
            $bool = M('adoption')
                ->where('id = '.$id)
                ->delete();
            $state = 0;
        }else {
            $bool = M('adoption')->data(array(
                'question_id' => $post['question_id'],
                'user_id' => $this->user_id,
                'accountant_id' => $post['accounting_id'],
                'add_time' => time(),
            ))->add();
            $state = 1;
        }

        if($bool){
            if($state){
                M('accountant_users')->where('au_id = '.$post['accounting_id'])->setInc('adoption_num' , 1);
            }else{
                M('accountant_users')->where('au_id = '.$post['accounting_id'])->setDec('adoption_num' , 1);
            }
            $usersModel = new UsersModel();
            $count = $usersModel->getAdoptionNum($post['question_id'],$post['accounting_id']);
            $res['status'] = true;
            $res['num'] = $count;
            $res['state'] = $state;
        }else{
            $res['status'] = false;
        }

        return $res;
    }

    public function collect($post = array()){
        $res = array('status' => 0 , 'msg' => '');

        $accModel = new AccountantModel();
        $id = $accModel->hasCollect($post['question_id']);
        if($post['collect_state']){
            if(!$id){
                $bool = M('collect')->data(array(
                    'question_id' => $post['question_id'],
                    'user_id' => $this->user_id,
                    'add_time' => time(),
                ))->add();

            }else{
                $bool = true;
            }
        }else{
            if($id){
                $bool = M('collect')
                    ->where('id = '.$id)
                    ->delete();
            }else{
                $bool = true;
            }
        }

        $res['status'] = $bool ? true : false;
        return $res;
    }

}
